import * as step from '@flow-step/step-toolkit'
import {RosInterface} from './ros'
import {ListStacksRequest, ListStacksResponse, ListStacksResponseBody} from '@alicloud/ros20190910'
import {IParams} from './params'
import {isNotEmpty} from './util'



export async function checkStackExist(params: IParams, ros: RosInterface) {
    let stackNames: string [] = []
    let stackName = params.STACK_NAME
    stackNames.push(stackName)
    const request = new ListStacksRequest({
        regionId: params.REGION_ID,
        stackName: stackNames,
        pageSize: 1,
        pageNumber: 1
    })
    let response: ListStacksResponse
    try {
        response = await ros.listStacks(request)
    } catch (error:any) {
        step.error(`Failed to listStacks. Code: ${error?.code}, Message: ${error.data?.Message}, RequestId: ${error.data?.RequestId}`)
        if (!isNotEmpty(error.data?.Message)) {
            step.error(`Unexpected listStacks error. Error: ${JSON.stringify(error, null, 2)}`);
        }
        return false
    }

    let result: ListStacksResponseBody | any = response.body

    const stackInfo = result.stacks
    step.info(`Stack info is ${JSON.stringify(stackInfo, null, 2)}`);
    if (isNotEmpty(stackInfo)) {
        step.info(`${params.STACK_NAME} exists. About to start updating stacks.`);
        return stackInfo[0].stackId
    } else {
        step.info(`${params.STACK_NAME} does not exist. About to start creating stacks.`);
        return false
    }
}